package com.chen;

/**
 * 下载单张图片
 * 4k壁纸
 */

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownLoad {
    public static void main(String[] args) {
        String path = "https://pic.netbian.com/4kdongman/index_7.html";
        //设置名称
        int name = 1;
        //System.out.println(path);

        //全局变量
        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            //把HTML解析为document对象
            //把页面包装为url对象
            URL url = new URL(path);
            //通过jsouop解析器来解析页面，获得dom对象
            try {
                //Document document = Jsoup.parse(url, 30000);
                //System.out.println(document);
                //通过dom对象对应的标签名称获取数据
                //得到大图页面

                String href = "https://pic.netbian.com/tupian/27115.html";

                String imgSrc = "https://pic.netbian.com/uploads/allimg/210323/010224-1616432544d68a.jpg";
                System.out.println(imgSrc);
                //打开链接
                //创建url对象，把路径作为参数传入
                URL imgsrcUrl = new URL(imgSrc);
                //通过url对象的openConnection()方法，打开图片链接
                URLConnection connection = imgsrcUrl.openConnection();
                //下载图片
                inputStream = connection.getInputStream();
                //选择路径
                String outFile = "D:\\img\\" + name + ".jpg";
                name++;
                //创建输出流
                outputStream = new FileOutputStream(outFile);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                System.out.println("下载完成");


            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
